const tool = require('../tools/tool')

module.exports = {
    adminLogin: {
        exp: '管理员登录',
        method: 'post',
        async func(data) {
            let re = await tool.methods.user().getSingleInfo.byUserName(data.param.username)
            if (re === undefined) {
                throw '用户不存在'
            } else {
                if (!re.admin) throw '需要管理员权限'
                let token = await tool.methods.user().genToken(re.id)
                await tool.methods.user().setToken(re.id, token)
                re = await tool.methods.user().getSingleInfo.byUserName(data.param.username)
                delete re.password
                return re
            }
        }
    },
    login: {
        exp: '登录',
        method: 'post',
        async func(data) {
            let re = await tool.methods.user().getSingleInfo.byUserName(data.param.username)
            if (re === undefined) {
                throw '用户不存在'
            } else {
                let token = await tool.methods.user().genToken(re.id)
                await tool.methods.user().setToken(re.id, token)
                re = await tool.methods.user().getSingleInfo.byUserName(data.param.username)
                delete re.password
                return re
            }
        }
    },
    autoLogin: {
        exp: '自动登录',
        method: 'post',
        async func(data) {
            if (!data.param.token) throw '缺少token'
            let userData = await tool.methods.user().getSingleInfo.byToken(data.param.token)
            if (userData === undefined) throw '请重新登录'
            delete userData.password
            let token = await tool.methods.user().genToken(userData.id)
            await tool.methods.user().setToken(userData.id, token)
            userData = await tool.methods.user().getSingleInfo.byId(userData.id)
            return userData
        }
    }
}